import React, { useState, useEffect } from 'react';
import { List, Card, Button, Space, Typography, Modal, Form, Input, Empty, Tooltip, App } from 'antd';
import { PlusOutlined, FolderOutlined, FolderOpenOutlined, TagOutlined, CheckOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { X } from 'lucide-react';
import { Calendar } from 'lucide-react';
import { useToast } from '../contexts/ToastContext';
import { ProjectConfig } from '../types';

const { Title, Text } = Typography;

interface ProjectListProps {
  projects: ProjectConfig[];
  onAddProject: (projectPath: string, projectName: string) => Promise<boolean>;
  onRemoveProject: (projectId: string) => Promise<void>;
  onSelectProject: (project: ProjectConfig) => void;
}

export const ProjectList: React.FC<ProjectListProps> = ({
  projects,
  onAddProject,
  onRemoveProject,
  onSelectProject
}) => {
  console.log('[ProjectList] 接收到的项目数据:', projects);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newProjectName, setNewProjectName] = useState('');
  const [selectedPath, setSelectedPath] = useState('');
  const [adding, setAdding] = useState(false);
  const [showPathInput, setShowPathInput] = useState(false);
  const [tempDirName, setTempDirName] = useState('');
  const [form] = Form.useForm();
  const { modal } = App.useApp();

  const handleSelectDirectory = async () => {
    try {
      // 浏览器环境，使用File System Access API或手动输入
      if ('showDirectoryPicker' in window) {
        try {
          const dirHandle = await (window as any).showDirectoryPicker();
          
          // 由于浏览器安全限制，无法获取完整的文件系统路径
          // 显示路径输入对话框
          setTempDirName(dirHandle.name);
          setShowPathInput(true);
        } catch (error: any) {
          if (error.name !== 'AbortError') {
            console.error('选择目录失败:', error);
          }
        }
      } else {
        // 不支持File System Access API，直接显示手动输入
        setTempDirName('');
        setShowPathInput(true);
      }
    } catch (error) {
      console.error('选择目录失败:', error);
      alert('选择目录失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  const handleConfirmPath = (inputPath: string) => {
    if (inputPath && inputPath.trim()) {
      const trimmedPath = inputPath.trim();
      setSelectedPath(trimmedPath);
      const dirName = trimmedPath.split(/[\\\/]/).pop() || tempDirName;
      const projectName = dirName || '手动添加的项目';
      setNewProjectName(projectName);
      
      // 更新表单字段值
      form.setFieldsValue({
        path: trimmedPath,
        name: projectName
      });
    }
    setShowPathInput(false);
    setTempDirName('');
  };

  const handleCancelPathInput = () => {
    setShowPathInput(false);
    setTempDirName('');
  };

  const handleAddProject = async (values: { path: string; name: string }) => {
    const { path, name } = values;
    if (!path || !name.trim()) return;

    try {
      setAdding(true);
      const success = await onAddProject(path, name.trim());
      if (success) {
        setShowAddForm(false);
        setNewProjectName('');
        setSelectedPath('');
        form.resetFields();
      }
    } finally {
      setAdding(false);
    }
  };

  const handleCancelAdd = () => {
    setShowAddForm(false);
    setNewProjectName('');
    setSelectedPath('');
    form.resetFields();
  };

  const handleRemoveProject = (projectId: string, projectName: string) => {
    modal.confirm({
      title: '删除项目',
      content: `确定要删除项目 "${projectName}" 吗？此操作不可撤销。`,
      icon: React.createElement(ExclamationCircleOutlined),
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        await onRemoveProject(projectId);
      }
    });
  };

  return (
    <div className="space-y-4">
      {/* 路径输入对话框 */}
      <Modal
        title={
          <Space>
            <FolderOutlined />
            <span>输入项目路径</span>
          </Space>
        }
        open={showPathInput}
        onCancel={handleCancelPathInput}
        footer={null}
        width={500}
      >
        {tempDirName && (
          <div style={{ marginBottom: 16, padding: 12, backgroundColor: '#f0f9ff', border: '1px solid #0ea5e9', borderRadius: 8 }}>
            <Text strong style={{ color: '#0369a1' }}>
              已选择目录: {tempDirName}
            </Text>
            <br />
            <Text type="secondary" style={{ fontSize: '12px' }}>
              由于浏览器安全限制，请输入该目录的完整路径
            </Text>
          </div>
        )}
        <Form
          onFinish={(values) => handleConfirmPath(values.path)}
          layout="vertical"
        >
          <Form.Item
            label="项目完整路径"
            name="path"
            rules={[{ required: true, message: '请输入项目路径' }]}
          >
            <Input
              autoFocus
              placeholder={tempDirName ? `例如: C:\\Users\\YourName\\Projects\\${tempDirName}` : "例如: C:\\Users\\YourName\\Projects\\MyProject"}
              onPressEnter={(e) => handleConfirmPath(e.currentTarget.value)}
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancelPathInput}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      {/* 添加项目按钮 */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setShowAddForm(true)}
        >
          添加新项目
        </Button>
      </div>
      {/* 添加项目表单 */}
      <Modal
        title={
          <Space>
            <PlusOutlined />
            <span>添加新项目</span>
          </Space>
        }
        open={showAddForm}
        onCancel={handleCancelAdd}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          onFinish={handleAddProject}
          layout="vertical"
          initialValues={{
            path: selectedPath,
            name: newProjectName
          }}
          key={`${selectedPath}-${newProjectName}`}
        >
          <Form.Item
            label={
              <Space>
                <FolderOutlined />
                <span>项目路径</span>
              </Space>
            }
            name="path"
            rules={[{ required: true, message: '请输入项目路径' }]}
          >
            <Space.Compact style={{ width: '100%' }}>
              <Form.Item name="path" noStyle>
                <Input
                  style={{ width: 'calc(100% - 100px)' }}
                  placeholder="输入项目路径或点击选择目录"
                />
              </Form.Item>
              <Button
                style={{ width: '100px' }}
                icon={<FolderOpenOutlined />}
                onClick={handleSelectDirectory}
              >
                选择目录
              </Button>
            </Space.Compact>
          </Form.Item>
          
          {!('showDirectoryPicker' in window) && (
            <div style={{ marginBottom: 16, padding: 12, backgroundColor: '#fff7ed', border: '1px solid #fb923c', borderRadius: 8 }}>
              <Text type="warning" style={{ fontSize: '12px' }}>
                您的浏览器不支持目录选择API，请手动输入项目路径
              </Text>
            </div>
          )}
          
          <Form.Item
            label={
              <Space>
                <TagOutlined />
                <span>项目名称</span>
              </Space>
            }
            name="name"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input
              placeholder="请输入项目名称"
            />
          </Form.Item>
          
          <Form.Item shouldUpdate style={{ marginBottom: 0, textAlign: 'right' }}>
            {({ getFieldsValue }) => {
              const { path, name } = getFieldsValue();
              return (
                <Space>
                  <Button onClick={handleCancelAdd}>
                    取消
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={adding}
                    disabled={!path || !name?.trim()}
                  >
                    {adding ? '添加中...' : '添加项目'}
                  </Button>
                </Space>
              );
            }}
          </Form.Item>
        </Form>
      </Modal>

      {/* 项目列表 */}
      {projects.length === 0 ? (
        <Empty
          image={<FolderOpenOutlined style={{ fontSize: 48, color: '#d1d5db' }} />}
          description={
            <div>
              <Title level={4} style={{ color: '#6b7280', marginBottom: 8 }}>还没有添加任何项目</Title>
              <Text type="secondary">开始添加您的第一个Git项目，生成专业的工作报告</Text>
            </div>
          }
        >
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setShowAddForm(true)}>
            添加第一个项目
          </Button>
        </Empty>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-6">
          {projects.map((project) => (
            <Card
              key={project.id}
              className="relative group h-full transition-all duration-300 hover:shadow-xl border border-gray-200 hover:border-primary-300 rounded-xl overflow-hidden bg-gradient-to-br from-white to-gray-50"
              style={{ minWidth: '320px' }}
              styles={{
                body: { padding: '24px', height: '100%' }
              }}
            >
              {/* 删除按钮 - 右上角 */}
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  handleRemoveProject(project.id, project.name);
                }}
                className="absolute top-3 right-3 w-8 h-8 bg-red-500 hover:bg-red-600 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-200 shadow-md hover:shadow-lg transform hover:scale-110 z-10"
                title="删除项目"
              >
                <X className="w-4 h-4" />
              </button>
              {/* 项目图标和基本信息 */}
              <div className="flex items-start space-x-4 mb-4">
                <div className="flex-shrink-0 w-12 h-12 bg-gradient-to-br from-primary-100 to-primary-200 rounded-xl flex items-center justify-center shadow-sm">
                  <FolderOutlined className="w-6 h-6 text-primary-600" />
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="text-lg font-semibold text-gray-900 truncate mb-1" title={project.name}>
                    {project.name}
                  </h3>
                  <p className="text-sm text-gray-500 truncate" title={project.path}>
                    {project.path}
                  </p>
                </div>
              </div>

              {/* 项目描述 */}
              {project.description && (
                <div className="mb-4">
                  <p className="text-sm text-gray-600 line-clamp-2" title={project.description}>
                    {project.description}
                  </p>
                </div>
              )}

              {/* 项目统计信息 */}
              <div className="flex items-center justify-between text-xs text-gray-500 mb-6">
                <span className="flex items-center">
                  <Calendar className="w-3 h-3 mr-1" />
                  {new Date(project.addedAt).toLocaleDateString()}
                </span>
                <span className="px-2 py-1 bg-green-100 text-green-700 rounded-full font-medium">
                  活跃
                </span>
              </div>

              {/* 操作按钮 */}
              <div className="flex mt-auto">
                <Button
                  type="primary"
                  size="middle"
                  icon={<CheckOutlined />}
                  onClick={() => onSelectProject(project)}
                  className="w-full h-10 rounded-lg font-medium shadow-sm hover:shadow-md transition-all duration-200"
                >
                  选择项目
                </Button>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};